/*
 * =====================================================================================
 *
 *       Filename:  simple_udp_svr.cpp
 *
 *    Description:  简单的UDP服务器
 *
 *        Version:  1.0
 *        Created:  2008年09月04日 20时58分54秒
 *       Revision:  none
 *       Compiler:  g++
 *
 *         Author:  ZhixiongHong (hzx), fishwarter@gmail.com
 *        Company:  Unioncast
 *
 * =====================================================================================
 */

#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

#define MAX_LINE 	1024

void comm(int sockfd);


int main(int argc, char** argv)
{
	if( argc != 2)
	{
		cout << "useage: " << argv[0] << " listenport " << endl;
		return -1;
	}
	
	unsigned short  listenPort = atoi(argv[1]);
	
	struct sockaddr_in	serverAddr;
	
	int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if( sockfd < 0 )
	{
		cout << "can't create socket " << endl;
		return -1;
	}
	
	bzero(&serverAddr, sizeof(serverAddr));
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	serverAddr.sin_port = htons(listenPort);
	
	const int on = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on ,sizeof(on));

	int retInt = bind(sockfd, (sockaddr *)&serverAddr, sizeof(serverAddr));
	if( retInt )
	{
		cout << "cant't bind on " << listenPort;
		return -1;
	}
		
	comm(sockfd);
	return 0;
}


void comm(int sockfd)
{
	int 		recvLen;
	char 		msg[MAX_LINE];
	struct sockaddr_in	cliAddr;
	for(;;)
	{
		socklen_t addrLen = sizeof(cliAddr);
		recvLen = recvfrom(sockfd, msg, MAX_LINE, 0, (sockaddr *)&cliAddr, &addrLen);
		//cout << "recv message:  " << msg << "  from " << inet_ntoa(cliAddr.sin_addr) << ":" << ntohs(cliAddr.sin_port) << endl;
		//sendto(sockfd, msg, recvLen, 0, (sockaddr *)&cliAddr,  addrLen);
	}
}
	

